<template xmlns:v-bind="http://www.w3.org/1999/xhtml">
  <div class="el-input el-input--small">
    <input class="el-input__inner"
           v-bind:value="formatValue"
           ref="input"
           placeholder="请输入"
           @input="updateValue($event.target.value)"
           @blur="onBlur"
           @focus="onFocus"/>
  </div>
</template>

<script>
  export default {
    props: {
      value: {
        type: [String, Number],
        default: 0,
        desc: '数值'
      }
    },
    data() {
      return {
        focused: false
      }
    },
    computed: {
      formatValue() {
        if (this.focused) {
          return this.unFormatMoney(this.value)
        } else {
          return this.format(this.value)
        }
      }
    },
    methods: {
      format(value, decimals) {
        const digitsRE = /(\d{3})(?=\d)/g
        value = parseFloat(value)
        if (!isFinite(value) || (!value && value !== 0)) return ''
        decimals = decimals != null ? decimals : 2
        let stringified = Math.abs(value).toFixed(decimals)
        let _int = decimals
          ? stringified.slice(0, -1 - decimals)
          : stringified
        let i = _int.length % 3
        let head = i > 0
          ? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
          : ''
        let _float = decimals
          ? stringified.slice(-1 - decimals)
          : ''
        let sign = value < 0 ? '-' : ''
        return sign + head +
          _int.slice(i).replace(digitsRE, '$1,') +
          _float
      },
      updateValue(value) {
        let formatValue = this.unFormatMoney(value)
        this.$emit('input', formatValue)
      },
      onBlur() {
        this.focused = false
        this.$emit('blur')
        this.dispatch('ElFormItem', 'el.form.blur', [this.value])
      },
      onFocus(event) {
        this.focused = true
        setTimeout(() => {
          event.target.select()
        }, 0)
      },
      dispatch(componentName, eventName, params) {
        let parent = this.$parent || this.$root
        let name = parent.$options.componentName
        while (parent && (!name || name !== componentName)) {
          parent = parent.$parent
          if (parent) {
            name = parent.$options.componentName
          }
        }
        if (parent) {
          parent.$emit.apply(parent, [eventName].concat(params))
        }
      }
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>

</style>
